Pointers inside a structure [on hold]

Posted by user3402552 on Programmers See other posts from Programmers or by user3402552
Published on 2014-06-02T16:06:30Z Indexed on 2014/06/02 21:45 UTC
Read the original article Hit count: 206

Filed under:

I have the next program:

#include<stdio.h>
#include<stdlib.h>

struct a
{
    char *ch;
    char *str;
};

int main()
{
    struct a s1;
    char ptr[100];
    int m, n;
    printf("\n Enter a string : ");
    gets(ptr);
    m = strlen(ptr);
    s1.ch = (char *)malloc(strlen(ptr) * sizeof(char));
    if(s1.ch)
    {
        strcpy(s1.ch, ptr);
    }
    else
    {
        printf("\n Alocation failed!\n");
    }
    printf("\n %s\n\n", s1.ch);
    while(*s1.ch)
    {
        printf(" %c", *(s1.ch));
        s1.ch++;
    }
    printf("\n\n");
    s1.ch = s1.ch - m;
    printf("\n\n\n %s \n\n", s1.ch);
}

Is this ok this program in this way ?

I mean the pointers should not be initialized ?

And if it is not ok, why compile it without errors?

© Programmers or respective owner

Related posts about c